package com.vng.zing.survey.data;

import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import kyotocabinet.DB;
import org.apache.log4j.Logger;
import org.cliffc.high_scale_lib.NonBlockingHashMap;
import com.vng.zing.survey.thrift.model.Error;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author kienpd
 */
public class IDSurveyMaxData extends Base{
    private static final Lock createLock_ = new ReentrantLock();
    private static IDSurveyMaxData _instance = null;
    private final DB db;

    public IDSurveyMaxData() {
        db = new DB();
        if (!db.open("database/idsurveymax.kch", DB.OWRITER | DB.OCREATE| DB.OAUTOTRAN)) {
            System.err.println("open error: " + db.error());
        }

    }

    public static IDSurveyMaxData getInstance() {
        if (_instance == null) {
            createLock_.lock();
            try {
                if (_instance == null) {
                    _instance = new IDSurveyMaxData();
                }
            } finally {
                createLock_.unlock();
            }
        }
        return _instance;
    }

    public int getMaxIDSurvey() {
        String maxId = db.get("MAX_IDSURVEY");
        if (maxId == null) {
            if (!db.set("MAX_IDSURVEY", "1")) {
                System.out.println("Database error");
                return 0;
            }
            return 1;

        }
        return Integer.parseInt(maxId);

    }

    public Error setMaxIDSurvey(int id) {

        if (!db.set("MAX_IDSURVEY", String.valueOf(id))) {
            return Error.ERR_SYSTEM;
        }
        return Error.SUCCESS;

    }

    public int incMaxIDSuvery() {
       db.begin_transaction(false);
        long id;
        
            id = db.increment("MAX_IDSURVEY", 1, 0);
            if (id == Long.MIN_VALUE || id == Long.MAX_VALUE) {
                System.err.println("Erro max id survey");
            }
        db.end_transaction(true);
        return (int) id;
    }

}
